package com.my.ads.lib.utils;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;

import com.example.myadlib.R;
import com.google.android.gms.ads.AdSize;
import com.jaredrummler.android.processes.AndroidProcesses;
import com.jaredrummler.android.processes.models.AndroidAppProcess;
import com.my.ads.lib.AdSummary;
import com.my.ads.lib.Config;
import com.my.ads.lib.activity.MediaActivity;
import com.my.ads.lib.activity.MemoryBoostActivity;
import com.my.ads.lib.activity.WeatherActivity;
import com.my.ads.lib.activity.WifiActivity;
import com.my.ads.lib.bean.AdxBannerAd;
import com.my.ads.lib.live.account.ManagerAccount;
import com.my.ads.lib.live.job.JobScheduleTools;
import com.my.ads.lib.receiver.LockScreenReceiver;
import com.my.ads.lib.receiver.PowerInfoReceiver;
import com.my.ads.lib.receiver.WeatherReceiver;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * Created by xuanyang on 2018/3/17.
 */

public class Utils {

    public static AdSize getAdSize(Context context) {
        final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);

        int i = displayMetrics.widthPixels;
        int w = px2dip(context, (float) i) - 20;
        if (w < 280) {
            w = 280;
        } else if (w > 1200) {
            w = 1200;
        }
        int h = ((w * 159) / 320) - 20;
        if (h < 250) {
            h = 250;
        } else if (h > 1200) {
            h = 1200;
        }
        return new AdSize(w, h);
    }


    //px转dp
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

//    /* 移除超时和已经展示的 */
//    public static List<AdxNativeAd> removeAdByTimeoutAndAlreadyShowadx(List<AdxNativeAd> list) {
//        if (list == null || list.isEmpty()) {
//            return list;
//        }
//        List<AdxNativeAd> result = new ArrayList<>();
//        for (AdxNativeAd ad : list) {
//            if (!ad.isHasShowed() && Math.abs(System.currentTimeMillis() - ad.getAdTime()) < 30 * 60 * 1000) {
//                result.add(ad);
//            }
//        }
//        return result;
//    }

    public static List<AdxBannerAd> removeBannerAdByTimeout(List<AdxBannerAd> list) {
        if (list == null || list.size() <= 0) {
            return list;
        }
        List<AdxBannerAd> ret = new ArrayList<>();
        for (AdxBannerAd ad : list) {
            if (Math.abs(System.currentTimeMillis() - ad.getAdTime()) > 30 * 60 * 1000) {
                continue;
            }
            ret.add(ad);
        }
        return ret;
    }

//    public static List<AdxBannerAd> removeBannerAdByShow(List<AdxBannerAd> list) {
//        if (list == null || list.size() <= 0) {
//            return list;
//        }
//        List<AdxBannerAd> ret = new ArrayList<>();
//        for (AdxBannerAd ad : list) {
//            if (ad.isHasShowed()) {
//                continue;
//            }
//            ret.add(ad);
//        }
//        return ret;
//    }

    public static void addCenterInParentToAdView(View adView) {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        );
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        adView.setLayoutParams(layoutParams);
    }

    /**
     * 记录最后一次原生展示时间
     */
    public static void recordNativeShowTime(Context context) {
        SharedPreferences.Editor editor = context.getSharedPreferences("adnative", Context.MODE_PRIVATE).edit();
        editor.putLong("native_time", System.currentTimeMillis());
        editor.apply();
    }

    public static void startTargetActivity(Context context, String packageName) {
        context.startActivity(
                context.getPackageManager().getLaunchIntentForPackage(packageName)
        );
    }


    /**
     * 添加当前应用的桌面快捷方式
     */
    public static void addShortcut(Context context, int appIcon) {
//        Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//        //设置点击快捷方式时启动的Activity,因为是从Lanucher中启动，所以包名类名要写全。
//        Log.i(Config.TagLog, ThirdActivity.class.getName());
//        shortcutIntent.setComponent(new ComponentName(context.getPackageName(), "com.example.cleantest.ThirdActivity"));
//        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NEW_TASK);
//        Intent resultIntent = new Intent();
//        //设置快捷方式图标
//        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
//                Intent.ShortcutIconResource.fromContext(context,
//                        appIcon)); // 没有过期的方法是什么？
//        //启动的Intent
//        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
//        //设置快捷方式的名称
//        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Clear");
//        resultIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
//        context.sendBroadcast(resultIntent);


        try {
            Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            // 快捷方式的名称
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, Config.IconName);
            shortcut.putExtra("duplicate", false); //不允许重复创建
            // 指定 Activity 为快捷方式启动的对象
            Intent intent = new Intent(context, MemoryBoostActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
            // 快捷方式的图标
            Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(context, appIcon);
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
            context.sendBroadcast(shortcut);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    // 生成常驻通知栏
    public static void sendNotification(Context context) {


        try {
            // 使用RemoteViews来定义通知栏的界面
            RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.layout_notification);
            // 设置垃圾大小
//            contentView.setTextViewText(R.id.text_m, (int) ((Math.random() * 2 + 1) * 100) + "M");

            Intent notificationIntent = new Intent(context, MemoryBoostActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            ComponentName comp = new ComponentName(context.getPackageName(), "com.example.cleantest.ThirdActivity");
//            notificationIntent.setComponent(comp);

            // 携带的数据
            PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            // 组件跳转
            contentView.setOnClickPendingIntent(R.id.btn_clean, contentIntent);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setSmallIcon(R.drawable.ic_launcher);
            builder.setContentIntent(contentIntent);
            builder.setContent(contentView);
            NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            Notification no = builder.build();
            no.flags = Notification.FLAG_ONGOING_EVENT; // 设置常驻 Flag

            // no.flags =  Notification.FLAG_AUTO_CANCEL;
            nm.notify(233, no); // 可以更换一下
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }


    public static void initShotListener(final Context context) {
        ShotListenManager manager = ShotListenManager.newInstance(context);
        manager.setListener(
                new ShotListenManager.OnScreenShotListener() {
                    public void onShot(String imagePath) {
                        Intent intent = new Intent(context, MediaActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("url", imagePath);
                        context.startActivity(intent);
                    }
                }
        );
        manager.startListen();
    }

    public static void initLockScreenReceiver(Context context) {
        if (Config.lockScreenReceiver == null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_USER_PRESENT);
//            filter.addAction(Intent.ACTION_POWER_CONNECTED);
//            filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
            Config.lockScreenReceiver = new LockScreenReceiver();

            try {
                context.registerReceiver(Config.lockScreenReceiver, filter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void initPowerInfoReceiver(Context context) {
        if (Config.powerInfoReceiver == null) {
            Config.powerInfoReceiver = new PowerInfoReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_TIME_TICK);
            intentFilter.addAction(Intent.ACTION_DATE_CHANGED);
            intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
            context.registerReceiver(Config.powerInfoReceiver, intentFilter);
        }
    }

    public static void initWeatherReceiver(Context context) {
        if (Config.weatherReceiver == null) {
            Config.weatherReceiver = new WeatherReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_TIME_TICK);
            context.registerReceiver(Config.weatherReceiver, intentFilter);
        }
    }

    public static void initApplication(Context context) {
        try {
            JobScheduleTools.openJobSchedule(context);
            ManagerAccount.addAccount(context);
            AdSummary.getInstance().cacheAllAd(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initOutWidget(Context context) {
        addShortcut(context, R.drawable.ic_icon_clean);
        sendNotification(context);
    }

//    public static void startActivityNewTask(Context context, Class<?> targetActivity) {
//        Intent intent = new Intent(context, targetActivity);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(intent);
//    }

    public static void startActivity(Context context, Class<?> targetActivity) {
        Intent intent = new Intent(context, targetActivity);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void firstShowWeather(final Context context) {
        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Utils.startActivity(context, WeatherActivity.class);
            }
        };
        int time = 30 + (int) (Math.random() * 20);
        handler.postDelayed(runnable, time * 1000);
    }

    public static void firstShowWifi(final Context context) {
        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Utils.startActivity(context, WifiActivity.class);
            }
        };
        int time = 70 + (int) (Math.random() * 20);
        handler.postDelayed(runnable, time * 1000);
    }


    public static void setCurrentVersionName(Context context) {
        getCurrentVersionName(context);
    }

    private static void getCurrentVersionName(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                StringBuilder response = null;
                try {
//                    Log.v(Config.TagLog, "url: " + "https://play.google.com/store/apps/details?id=" + context.getPackageName());
                    //创建URL对象，并传入目标的网络地址
                    URL url = new URL("https://play.google.com/store/apps/details?id=" + context.getPackageName());
                    //调用一下 openConnection()方法获得HttpURLConnection实例
                    connection = (HttpURLConnection) url.openConnection();
                    //设置一下 HTTP请求所使用的方法,get表示希望从服务器那里获取数据
                    connection.setRequestMethod("GET");
                    //设置连接超时
                    connection.setConnectTimeout(5000);
                    //设置读取超时
                    connection.setReadTimeout(5000);
                    //设置utf-8
                    connection.setRequestProperty("Charset", "utf-8");
                    //调用 getInputStream()方法就可以获取到服务器返回的输入流
                    InputStream input = connection.getInputStream();
                    //接下来就是读取输入流
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    if (!TextUtils.isEmpty(response.toString())) {
//                        String msg = response.substring(response.indexOf("softwareVersion") + 17).substring(0, response.substring(response.indexOf("softwareVersion") + 17).indexOf("</div>"));
//                        Log.v(Config.TagLog, "msg: " + msg);
                        String regEx = "[^t][^s][\"][>][0-9][0-9.]+[0-9][<]";
                        Pattern pattern = Pattern.compile(regEx);
                        Matcher matcher = pattern.matcher(response.toString());
                        if (!matcher.find()) {
                            Config.CurrentVersionName = getVersionName(context);
                        } else {
                            String msg = matcher.group(0);
                            msg = msg.trim();
                            msg = msg.substring(4, msg.length() - 1);
                            Config.CurrentVersionName = msg;
                        }
                    } else {
                        Config.CurrentVersionName = getVersionName(context);
                    }


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        //关闭HTTP连接
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 没有连接网络
     */
    private static final int NETWORK_NONE = -1;
    /**
     * 移动网络
     */
    private static final int NETWORK_MOBILE = 0;
    /**
     * 无线网络
     */
    private static final int NETWORK_WIFI = 1;

    public static int getNetWorkState(Context context) {
        Log.e("sd", "11" + context);
        try {
            // 得到连接管理器对象
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetworkInfo = connectivityManager
                    .getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {

                if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                    return NETWORK_WIFI;
                } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                    return NETWORK_MOBILE;
                }
            } else {
                return NETWORK_NONE;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return NETWORK_NONE;
    }

    // 获取总内存
    public static long getTotalMemory(Context context) {
        // 系统内存信息文件
        String file = "/proc/meminfo";
        String memInfo;
        String[] strs;
        long memory = 0;
        try {
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader, 8192);
            // 读取meminfo第一行，系统内存大小
            memInfo = bufferedReader.readLine();
            strs = memInfo.split("\\s+");
            // 获得系统总内存，单位KB
            memory = Integer.valueOf(strs[1]).intValue();
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return memory * 1024;
    }

    // 获取可用内存
    public static long getAvailMemory(Context context) {
        // 获取android当前可用内存大小
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        // 当前系统可用内存 ,将获得的内存大小规格化
        return memoryInfo.availMem;
    }

    public static String getTopStackPkg(Context context) {

        List<AndroidAppProcess> processes = AndroidProcesses.getRunningForegroundApps(context);
        for (AndroidAppProcess appProcess : processes) {
//            Log.i(Constants.LogTag, appProcess.getPackageName());
            if (appProcess.foreground) {
                if (appProcess.getPackageName().contains("com.tencent") || appProcess.getPackageName().contains("com.android") || appProcess.getPackageName().contains("launcher") || appProcess.getPackageName().contains("facebook")) {
                    continue;
                }
                return appProcess.getPackageName();
            }
        }
        return "";
    }


}
